<template>
  <div class="menu-management">
    <div class="page-header">
      <h2>{{ $t('common.menuManagement') }}</h2>
      <p>{{ $t('common.menuManagementDescription') }}</p>
    </div>
    
    <div class="search-container">
      <div class="search-item">
        <label>{{ $t('menu.menuName') }}:</label>
        <InputText v-model="searchParams.menuName" placeholder="{{ $t('common.pleaseInput') }}" />
      </div>
      <div class="search-item">
        <label>{{ $t('menu.menuType') }}:</label>
        <Dropdown
          v-model="searchParams.menuType"
          :options="menuTypeOptions"
          placeholder="{{ $t('common.pleaseSelect') }}"
          optionValue="value"
          optionLabel="label"
        />
      </div>
      <div class="search-item">
        <label>{{ $t('menu.status') }}:</label>
        <Dropdown
          v-model="searchParams.status"
          :options="statusOptions"
          placeholder="{{ $t('common.pleaseSelect') }}"
          optionValue="value"
          optionLabel="label"
        />
      </div>
      <div class="search-actions">
        <Button @click="search" icon="pi pi-search">{{ $t('common.search') }}</Button>
        <Button @click="reset" icon="pi pi-refresh">{{ $t('common.reset') }}</Button>
        <Button @click="handleAdd" icon="pi pi-plus" severity="success">{{ $t('common.add') }}</Button>
      </div>
    </div>
    
    <div class="table-container">
      <DataTable
        :value="menuStore.getMenuList"
        :loading="menuStore.getLoading"
        :paginator="true"
        :rows="searchParams.pageSize"
        :first="(searchParams.page - 1) * searchParams.pageSize"
        :totalRecords="menuStore.getMenuTotal"
        @page="onPageChange"
        @sort="onSortChange"
        rowHover
      >
        <Column field="id" header="{{ $t('menu.menuId') }}" sortable></Column>
        <Column field="menuName" header="{{ $t('menu.menuName') }}" sortable>
          <template #body="{ data }">
            <div :style="{ paddingLeft: `${(data.level || 0) * 20}px` }">
              <i :class="`pi ${data.icon}`" v-if="data.icon"></i>
              <span :style="{ marginLeft: data.icon ? '5px' : '0' }">{{ data.menuName }}</span>
            </div>
          </template>
        </Column>
        <Column field="parentId" header="{{ $t('menu.parentId') }}" sortable></Column>
        <Column field="menuType" header="{{ $t('menu.menuType') }}" sortable>
          <template #body="{ data }">
            {{ getMenuType(data.menuType) }}
          </template>
        </Column>
        <Column field="path" header="{{ $t('menu.path') }}"></Column>
        <Column field="component" header="{{ $t('menu.component') }}"></Column>
        <Column field="perms" header="{{ $t('menu.perms') }}"></Column>
        <Column field="orderNum" header="{{ $t('menu.orderNum') }}" sortable></Column>
        <Column field="status" header="{{ $t('common.status') }}">
          <template #body="{ data }">
            <Badge :severity="data.status === 1 ? 'success' : 'danger'">
              {{ data.status === 1 ? $t('common.active') : $t('common.inactive') }}
            </Badge>
          </template>
        </Column>
        <Column header="{{ $t('common.operate') }}" style="width: 15rem">
          <template #body="{ data }">
            <Button @click="handleAdd(data)" icon="pi pi-plus-circle" size="small" severity="info"></Button>
            <Button @click="handleEdit(data)" icon="pi pi-pencil" size="small"></Button>
            <Button @click="handleDelete(data.id)" icon="pi pi-trash" size="small" severity="danger"></Button>
            <Button @click="handlePermission(data.id)" icon="pi pi-lock" size="small" severity="warning"></Button>
          </template>
        </Column>
      </DataTable>
    </div>
    
    <!-- 添加/编辑对话框 -->
    <Dialog v-model:visible="dialogVisible" :header="dialogTitle" :modal="true" :style="{ width: '600px' }">
      <div class="form-container">
        <div class="form-item">
          <label>{{ $t('menu.parentMenu') }}:</label>
          <Dropdown
            v-model="formData.parentId"
            :options="menuTree"
            placeholder="{{ $t('common.pleaseSelect') }}"
            optionValue="id"
            optionLabel="menuName"
            :filter="true"
            :disabled="formData.parentId === '0'"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('menu.menuName') }} *:</label>
          <InputText v-model="formData.menuName" />
        </div>
        <div class="form-item">
          <label>{{ $t('menu.menuType') }} *:</label>
          <Dropdown
            v-model="formData.menuType"
            :options="menuTypeOptions"
            optionValue="value"
            optionLabel="label"
            @change="onMenuTypeChange"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('menu.path') }}:</label>
          <InputText v-model="formData.path" />
        </div>
        <div class="form-item" v-if="showComponent">
          <label>{{ $t('menu.component') }}:</label>
          <InputText v-model="formData.component" />
        </div>
        <div class="form-item">
          <label>{{ $t('menu.icon') }}:</label>
          <InputText v-model="formData.icon" placeholder="{{ $t('menu.iconPlaceholder') }}" />
        </div>
        <div class="form-item">
          <label>{{ $t('menu.perms') }}:</label>
          <InputText v-model="formData.perms" />
        </div>
        <div class="form-item">
          <label>{{ $t('menu.orderNum') }} *:</label>
          <InputNumber v-model="formData.orderNum" min="1" :max="999" />
        </div>
        <div class="form-item">
          <label>{{ $t('menu.status') }} *:</label>
          <Dropdown
            v-model="formData.status"
            :options="statusOptions"
            optionValue="value"
            optionLabel="label"
          />
        </div>
        <div class="form-item">
          <label>{{ $t('menu.isExternal') }}:</label>
          <InputSwitch v-model="formData.isExternal" />
        </div>
        <div class="form-item">
          <label>{{ $t('menu.isCache') }}:</label>
          <InputSwitch v-model="formData.isCache" />
        </div>
      </div>
      <template #footer>
        <Button @click="dialogVisible = false">{{ $t('common.cancel') }}</Button>
        <Button @click="handleSave" severity="primary">{{ $t('common.submit') }}</Button>
      </template>
    </Dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { useMenuStore } from '../../../store/modules/system/menu'
import type { Menu } from '../../../types/app.d'
import Button from 'primevue/button'
import InputText from 'primevue/inputtext'
import InputNumber from 'primevue/inputnumber'
import Dropdown from 'primevue/dropdown'
import DataTable from 'primevue/datatable'
import Column from 'primevue/column'
import Badge from 'primevue/badge'
import Dialog from 'primevue/dialog'
import InputSwitch from 'primevue/inputswitch'

const { t } = useI18n()
const menuStore = useMenuStore()

// 搜索参数
const searchParams = reactive({
  page: 1,
  pageSize: 10,
  menuName: '',
  menuType: null as string | null,
  status: null as number | null
})

// 状态选项
const statusOptions = [
  { label: t('common.active'), value: 1 },
  { label: t('common.inactive'), value: 0 }
]

// 菜单类型选项
const menuTypeOptions = [
  { label: t('menu.menuTypeDir'), value: 'M' },
  { label: t('menu.menuTypeMenu'), value: 'C' },
  { label: t('menu.menuTypeButton'), value: 'F' }
]

// 菜单树数据
const menuTree = ref<Menu[]>([])

// 对话框状态
const dialogVisible = ref(false)
const isEdit = ref(false)
const dialogTitle = ref('')

// 是否显示组件输入框
const showComponent = computed(() => {
  return formData.menuType === 'C' || formData.menuType === 'F'
})

// 表单数据
const formData = reactive<Partial<Menu>>({
  menuName: '',
  parentId: '0',
  menuType: 'M',
  path: '',
  component: '',
  icon: '',
  perms: '',
  orderNum: 0,
  status: 1,
  isExternal: false,
  isCache: false
})

// 初始化
const init = () => {
  menuStore.getMenuListAction(searchParams)
  loadMenuTree()
}

// 加载菜单树
const loadMenuTree = async () => {
  const treeData = await menuStore.getMenuTreeAction()
  if (treeData) {
    // 构建树结构，确保顶层节点显示
    const rootNode: Menu = { id: '0', menuName: t('common.rootMenu'), parentId: '-1', menuType: 'M', orderNum: 0, status: 1 }
    menuTree.value = [rootNode, ...treeData]
  }
}

// 获取菜单类型文本
const getMenuType = (menuType: string) => {
  const type = menuTypeOptions.find(option => option.value === menuType)
  return type ? type.label : ''
}

// 搜索
const search = () => {
  searchParams.page = 1
  menuStore.getMenuListAction(searchParams)
}

// 重置
const reset = () => {
  Object.assign(searchParams, {
    page: 1,
    pageSize: 10,
    menuName: '',
    menuType: null,
    status: null
  })
  menuStore.getMenuListAction(searchParams)
}

// 页面变化
const onPageChange = (event: any) => {
  searchParams.page = event.page + 1
  searchParams.pageSize = event.rows
  menuStore.getMenuListAction(searchParams)
}

// 排序变化
const onSortChange = (event: any) => {
  // 实际项目中可以根据排序字段和方向进行排序
  menuStore.getMenuListAction(searchParams)
}

// 菜单类型变化
const onMenuTypeChange = () => {
  // 根据菜单类型调整其他字段的默认值
  if (formData.menuType === 'F') {
    formData.component = ''
  }
}

// 添加菜单
const handleAdd = (parent?: Menu) => {
  isEdit.value = false
  dialogTitle.value = t('common.add') + t('common.menu')
  Object.assign(formData, {
    menuName: '',
    parentId: parent?.id || '0',
    menuType: 'M',
    path: '',
    component: '',
    icon: '',
    perms: '',
    orderNum: 0,
    status: 1,
    isExternal: false,
    isCache: false
  })
  dialogVisible.value = true
}

// 编辑菜单
const handleEdit = async (menu: Menu) => {
  isEdit.value = true
  dialogTitle.value = t('common.edit') + t('common.menu')
  await menuStore.getMenuInfoAction(menu.id)
  if (menuStore.getCurrentMenu) {
    Object.assign(formData, menuStore.getCurrentMenu)
  }
  dialogVisible.value = true
}

// 保存菜单
const handleSave = async () => {
  if (isEdit.value && formData.id) {
    const success = await menuStore.updateMenuAction(formData.id, formData)
    if (success) {
      dialogVisible.value = false
      menuStore.getMenuListAction(searchParams)
      menuStore.clearCurrentMenu()
      loadMenuTree()
    }
  } else {
    const success = await menuStore.createMenuAction(formData as Omit<Menu, 'id' | 'createTime' | 'updateTime'>)
    if (success) {
      dialogVisible.value = false
      menuStore.getMenuListAction(searchParams)
      loadMenuTree()
    }
  }
}

// 删除菜单
const handleDelete = async (id: string) => {
  // 检查是否有子菜单
  const hasChildren = menuStore.getMenuList.some(menu => menu.parentId === id)
  if (hasChildren) {
    alert(t('menu.hasChildrenCannotDelete'))
    return
  }
  
  if (confirm(t('common.confirmDelete'))) {
    const success = await menuStore.deleteMenuAction(id)
    if (success) {
      menuStore.getMenuListAction(searchParams)
      loadMenuTree()
    }
  }
}

// 设置权限
const handlePermission = (id: string) => {
  // 实际项目中可以打开权限设置对话框
  // 设置菜单权限
}

// 初始化加载数据
init()
</script>

<style scoped>
.menu-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #333;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.search-container {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  flex-wrap: wrap;
  align-items: flex-end;
}

.search-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.search-item label {
  font-weight: 500;
  color: #333;
}

.search-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;
}

.table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 20px;
}

.form-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.form-item label {
  font-weight: 500;
  color: #333;
}

.form-item input,
.form-item select,
.form-item .p-inputnumber {
  width: 100%;
}

.form-item .p-switch {
  align-self: flex-start;
  margin-top: 4px;
}
</style>